#!/usr/bin/env python

###
# Wifi + GPS fingerprint collection tool
# Copyright (c) 2008, Yura Zenevich, Jorge Silva, and Jamon Camisso
# Homepage http://wiki.scyp.atrc.utoronto.ca/wiki/WiFiPositioning
# Contact scyp@atrc.utoronto.ca
#    
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program, see enclosed file gpl-3.txt or browse to
# <http://www.gnu.org/licenses/gpl.txt>
###

import string
import sqlite3

class Search:

	def FindAllScansOnTheFloor(self, floorId):
		connection=sqlite3.connect("Addresses.db")
		try:
			scans = connection.execute("SELECT XOffset, YOffset FROM ScanInfos WHERE BuildingFloorId = ?;", [floorId]).fetchall()
		except: 
			print 'Error connecting to the database...'
		connection.close()
		if len(scans) == 0:
			return None
		return scans

	def FindFloorValue(self, floorId, macId):
		connection=sqlite3.connect("Addresses.db")
		try:
			orders = connection.execute("SELECT AVG(W.SignalStrength) FROM WifiScans AS W INNER JOIN ScanInfos S ON S.ScanTime = W.ScanTime AND S.BuildingFloorId = ? WHERE W.MacId = ?;", (floorId, macId)).fetchone()

		except: 
			print 'Error connecting to the database...'
		connection.close()
		if orders[0] is None:
			return 0
		return orders[0]

	def FindScanInfo(self, macId):
		connection=sqlite3.connect("Addresses.db")
		try:
			scanInfos = connection.execute("SELECT S.ScanTime, S.BuildingFloorId, S.XOffset, S.YOffset FROM ScanInfos AS S INNER JOIN WiFiScans AS W ON S.ScanTime = W.ScanTime WHERE W.MacId = ?;", [macId]).fetchall()
		except: 
			print 'Error connecting to the database...'
		connection.close()
		scanTimes = []
		x = []
		y = []
		floorIds = []
		for row in scanInfos:
			scanTimes.append(row[0])
			x.append(row[2])
			y.append(row[3])
			floorIds.append(row[1])
		return scanTimes, x, y, floorIds

	def FindWifiScan(self, scanT):
		connection=sqlite3.connect("Addresses.db")
		try:
			scanInfos2 = connection.execute("SELECT MacId, ScanTime, Count, SignalStrength FROM WiFiScans WHERE DateTime(ScanTime) = DateTime(?);", [scanT]).fetchall()
		except: 
			print 'Error connecting to the database...'
		connection.close()
		macs = []
		orderedss = []
		for row in scanInfos2:
			macs.append(row[0])
			orderedss.append(row[3])
		return macs, orderedss
